import { onMounted, onUnmounted, ref } from 'vue';

export interface ScheduleOptions {
  task: () => void;
  ms: number;
  clear?: () => void;
  create?: (hook: () => void) => void;
  destroy?: (hook: () => void) => void;
}

export const useSchedule = (option: ScheduleOptions): void => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const timeId = ref(null as any);

  if (!option.create) {
    option.create = onMounted;
  }

  option.create(async () => {
    if (!timeId.value) {
      timeId.value = setInterval(() => {
        option.task();
      }, option.ms);
    }
  });

  if (!option.destroy) {
    option.destroy = onUnmounted;
  }
  option.destroy(async () => {
    if (timeId.value) {
      clearInterval(timeId.value);
      if (option.clear) {
        option.clear();
      }
    }
  });
};
